package jal4eclipse.ui.editors.hyperlink;

import java.io.File;
import java.util.Map;
import java.util.TreeMap;

import jal4eclipse.jal.JALParser;
import jal4eclipse.jal.structure.JElement;
import jal4eclipse.ui.console.JALConsole;
import jal4eclipse.ui.editors.FileUtil;
import jal4eclipse.ui.editors.JALEditor;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.Assert;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.hyperlink.IHyperlink;
import org.eclipse.ui.IFileEditorInput;

public class JALHyperlink implements IHyperlink {

	private final IRegion fRegion;
	private JALEditor fEditor;

	public JALHyperlink(IRegion region, JALEditor editor) {
		Assert.isNotNull(region);
		fRegion = region;
		fEditor = editor;
	}

	public IRegion getHyperlinkRegion() {
		return fRegion;
	}

	public String getHyperlinkText() {
		return null;
	}

	public String getTypeLabel() {
		return null;
	}

	/**
	 * Try to find a definition and open it.
	 */
	public void open() {
		IDocument doc = fEditor.getDocument();
		String selectedWord = "";
		String lineStart = "";
		try {
			selectedWord = doc.get(fRegion.getOffset(), fRegion.getLength());
			int offset = fRegion.getOffset() - 1;
			while ((offset >= 0) && (!"\n".equals(doc.get(offset, 1)))) {
				lineStart = doc.get(offset, 1) + lineStart;
				offset--;
			}
		} catch (BadLocationException e) {
			JALConsole.write(e);
		}
		
		IFileEditorInput input = (IFileEditorInput) fEditor.getEditorInput();
		try {
			if ("include".equalsIgnoreCase(lineStart.trim())){
				IProject prj = input.getFile().getProject();
				IFile[] files = FileUtil.findAllReferencedFiles(prj);
				for (int i = 0;i<files.length;i++) {
					if (files[i].getName().equalsIgnoreCase(selectedWord+ ".jal")) {
						FileUtil.openJalFile(files[i]);
						break;
					}
				}

			} else {
				// if it's not an include, try to find method declaration
				Map includesMap = FileUtil.getIncludes(fEditor);
				Map all = new TreeMap();
				// find avaiable func / proc / vars
				File file = new File(input.getFile().getLocation().toOSString());
				JALParser.buildTree(file,includesMap,all);
				if (all.get(selectedWord) instanceof JElement) {
					JElement elem = (JElement) all.get(selectedWord);
					String filename = elem.getFilename();
					if (filename != null) {
						JALEditor edit = FileUtil.openJalFile(input.getFile().getProject(),filename);
						FileUtil.selectText(edit,selectedWord.toUpperCase());
					}
				}
			}
		} catch (Exception e1) {
			JALConsole.write(e1);
		}

	}

	

}
